(function (G) {
    const javaUrl = G.Storage.get('JAVAURL')
    G.vue({
        data: {
            inventoryId: null,
            unitsg: [], // 前一个页面传过来的所有机构
            updown: 1, // 控制隐藏和显示
            cameraimg: G.Storage.get('APIURL') + '/file/1594974455984164864', // 显示上传图标
            param: {}, // 参数
            img: [], // 上传的图片
            dispatchUser: null, // 指派用户
            resolveUser: null, // 分配人
            userNameList: [], // 所有用户名
            userList: [], // 所有用户
            index6: 0,
            urgency: 2, // 紧急程度
            source: 3, // 来源
            feedback: 3, // 监督员上报
            typeg: 1, // 案件类型
            firstType: 1, // 大类
            secondType: null, // 小类
            surplusTime: null, // 剩余处理时间
            applicant: null, // 申请人
            dispatchUserIDList: [], // 指派用户id，可能多个
            dispatchUserNameList: [], // 指派用户name，可能多个
            index1: 0, // 选择的第几个指派用户
            urgencyList: ['普通', '紧急'], // 紧急程度列表
            index2: 1, // 第几个紧急程度，默认紧急
            sourceList: ['12319', '城管通', '其他'], // 案件来源列表
            index3: 2, // 第几个案件来源，默认其他
            typeList: ['事件', '部件'], // 案件类型列表
            index4: 0, // 第几个案件类型
            firstTypeList: ['市容环境设施', '交通设施', '公共设施', '市容环境类', '宣传广告', '施工管理', '突发事件', '街面秩序'], // 大类列表
            index5: 0, // 第几个大类

            type: 1, // 考核类型编号1：日常检查考核；2：月度集中考核；3：公众监督考核；4： 重大事项考核
            picList: [],
            deductionList: [],
            gradeTotal: 0,
            address: '',
            APIURL: G.Storage.get('APIURL'),
            deductionIdList: [],
            description: '',
            roadId: 0,
            units: [],
            unitIndex: 0,
            latitude: '',
            longitude: '',
            unitId: '',
            unitName: '',
            taskId:'',
            tabIndex:0,
            tabs:[],
            timer:0,
            taskId2:'',//副流程Id
            zlxd:0,
            time:'',
            submiting:false
        },
        methods: {
            changeTab(event){
                let index = event.currentTarget ? event.currentTarget.dataset.index : event
                this.setData({
                    tabIndex:index
                })
                this.getGrid()
            },
            // 格式化时间
            formatDate(times) {
                var date = new Date(times);
                var year = date.getFullYear().toString(); //年份
                var month = (date.getMonth() + 1).toString(); //月份
                var day1 = date.getDate(); //日
                if (day1.toString().length == 1) {
                    var day = '0' + day1.toString()
                } else {
                    var day = day1.toString()
                }
                var hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()
                var minute = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
                var second = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
            },
            // 点击提交按钮
            submitg(koufenid) {
                let that = this
                let params = that.data.param
                console.log('---params', params);
                let editForm = {}
                let time1 = new Date()
                editForm.assessId = koufenid
                editForm.inventoryId = that.data.inventoryId
                editForm.location = that.data.address
                editForm.latitude = that.data.latitude
                editForm.longitude = that.data.longitude
                editForm.description = that.data.description ? that.data.description : ''
                if(!editForm.description && that.data.deductionList[0]) editForm.description = that.data.deductionList[0].name
                editForm.description = editForm.description.trim()
                if(that.data.tabIndex && that.data.units[that.data.unitIndex]) editForm.description += '(' + that.data.units[that.data.unitIndex].name + ')'
                editForm.img = that.data.picList.map(item => item.url).join(',')
                editForm.dispatchUser = that.data.dispatchUser
                editForm.dispatchTime = that.formatDate(time1)
                editForm.urgency = that.data.urgency
                editForm.source = that.data.source
                editForm.feedback = that.data.feedback
                editForm.type = that.data.type
                editForm.firstType = that.data.firstType
                editForm.secondType = that.data.secondType
                editForm.surplusTime = that.data.surplusTime
                editForm.applicant = that.data.applicant
                editForm.resolveUser = that.data.resolveUser ?? that.data.resolveUser
                editForm.status = 2
                editForm.applyType = 2,//简易案件
                editForm.unitId = that.data.units[that.data.unitIndex].unitId
                editForm.toUsers = that.data.dispatchUser
                editForm.gridName = that.data.units[that.data.unitIndex].name
                editForm.enterpriseName = that.data.units[that.data.unitIndex].enterpriseName
                editForm.username = that.data.units[that.data.unitIndex].userName
                editForm.unitName = that.data.units[that.data.unitIndex].unitName
                G.post('/api/model/g_case', editForm).then(res => {
                    if (!res.errorMsg) {
                        let addID = res.id
                        params.caseId = addID
                        //添加案件流程
                        G.post('/v1/task/add', {
                            userId: G.Storage.get('userInfo').userId,
                            flowId:'1589200662648983552',
                            // flowId: that.data.dispatchUser == null ? '1588901038793035776' : '1589200662648983552',
                            data: editForm,
                            title: editForm.description,
                            toUsers: editForm.dispatchUser,
                            unitId:editForm.unitId,
                            des:editForm.location
                        }).then(res1 => {
                            if (!res1.errorMsg) {
                                G.put('/api/model/g_case', {
                                    id: addID,
                                    taskID: res1.task.id
                                }).then(res2 => {
                                    if (!res2.errorMsg) {
                                        // wx.showToast({
                                        //     title: '操作成功',
                                        // })
                                        // if(koufenid){
                                            const eventChannel = this.getOpenerEventChannel()
                                            eventChannel.emit("addRecord", {
                                                koufenId: koufenid,
                                                caseId: res.id,
                                                taskId:res1.task.id
                                            })
                                            // G.alert('案件上报成功').then(()=>{
                                            //     this.$back()
                                            // })
                                        // }
                                        // wx.showToast({
                                        //     title: res2.errorMsg,
                                        //     icon: 'none'
                                        // })
                                        // G.alert('处理成功').then(res => {
                                        //     wx.navigateBack()
                                        // })
                                        // G.confirmx('操作成功',()=>{
                                        //     that.setData({taskId:res1.task.id})
                                        // },{
                                        //     confirmText:'确定',
                                        //     cancelText:'返回',
                                        //     cancel(){
                                        //         wx.navigateBack()
                                        //     }
                                        // })

                                    } else {
                                        wx.showToast({
                                            title: res2.errorMsg,
                                            icon: 'none'
                                        })
                                    }
                                })
                            } else {
                                wx.showToast({
                                    title: res1.errorMsg,
                                    icon: 'none'
                                })
                            }
                        })
                    } else {
                        wx.showToast({
                            title: res.errorMsg,
                            icon: 'none'
                        })
                    }
                })
            },
            // 输入剩余时间
            inputSurplusTime(e) {
                this.setData({
                    surplusTime: e.detail.value
                })
                console.log(this.data.surplusTime);
            },
            // 选择小类
            inputSecondType(e) {
                this.setData({
                    secondType: e.detail.value
                })
                console.log(this.data.secondType);
            },
            // 选择大类
            selectFirstType(e) {
                this.setData({
                    index5: e.detail.value,
                    firstType: parseInt(e.detail.value) + 1
                })
                console.log(this.data.firstType);
            },
            // 选择类型
            selectType(e) {
                this.setData({
                    index4: e.detail.value,
                    typeg: parseInt(e.detail.value) + 1
                })
                console.log(this.data.type);
            },
            // 案件来源选择
            selectSource(e) {
                this.setData({
                    index3: e.detail.value,
                    source: parseInt(e.detail.value) + 1
                })
                console.log(this.data.source);
            },
            // 选择紧急程度
            selectUrgency(e) {
                this.setData({
                    index2: e.detail.value,
                    urgency: parseInt(e.detail.value) + 1
                })
                console.log(this.data.urgency);
            },
            selectDispatchUser(e) {
                let that = this
                console.log('-----e', e.detail.value);
                let uesr = that.data.dispatchUserIDList[e.detail.value]
                that.setData({
                    index1: e.detail.value,
                    dispatchUser: uesr == '不指定' ? null : uesr
                })
                console.log(that.data.dispatchUser);
            },
            selectResolvUser(e) {
                let that = this
                console.log('-----e', e.detail.value);
                let uesr = that.data.userList[e.detail.value].id
                that.setData({
                    index6: e.detail.value,
                    resolveUser: uesr == '不指定' ? null : uesr
                })
                console.log(that.data.resolveUser);
            },
            // 输入详情描述
            inputChage(e) {
                console.log('---', e.detail.value, G.Storage.get('userInfo')['id']);
                this.setData({
                    description: e.detail.value
                })
            },
            // 选择图片
            chooseMediaa(tempFilePaths) {
                console.log('---tempFilePaths', tempFilePaths);
                let that = this
                // wx.chooseMedia({
                //     count: 9,
                //     mediaType: ['image'],
                //     sourceType: ['album', 'camera'],
                //     maxDuration: 30,
                //     camera: 'back',
                //     success(res) {
                let list = that.data.img
                for (let i in tempFilePaths) {
                    console.log('---1', i);
                    wx.uploadFile({
                        url: G.Storage.get('APIURL') + '/upload',
                        filePath: tempFilePaths[i].tempFilePath,
                        name: 'file',
                        header: {
                            'token': G.Storage.get('userInfo').token
                        },
                        success(rej) {
                            // console.log('---re', rej);
                            // let url1 = '/file/' + JSON.parse(rej.data).id
                            // list.push(url1)
                            // that.setData({
                            //     img: list
                            // })

                            let showUrl = JSON.parse(rej.data).id
                            let url = G.Storage.get('APIURL') + '/file/' + showUrl
                            let uploadList = [...that.data.picList, {
                                url,
                                showUrl
                            }]
                            console.log(uploadList, 'uploadList')
                            that.setData({
                                picList: uploadList,
                            })
                        },
                        fail(err) {
                            console.log(err)
                        }
                    });
                }
                // for (var k in tempFilePaths) {
                //     that.uploadRequest(tempFilePaths[k].tempFilePath)
                // }
                //     }
                // })
            },
            // 微信图片调用upload
            uploadRequestg(img) {
                wx.uploadFile({
                    url: G.Storage.get('APIURL') + '/upload',
                    filePath: img,
                    name: 'file',
                    header: {
                        'token': G.Storage.get('userInfo').token
                    },
                    success(rej) {
                        console.log('---rej.data', rej.data);
                        return JSON.parse(rej.data).id
                    },
                    fail(err) {
                        console.log(err)
                    }
                });
            },
            // 隐藏或者收起默认项
            updown() {
                let that = this
                that.setData({
                    updown: that.data.updown == 1 ? 2 : 1
                })
            },
            // 处理页面传参
            getInitParam(jsonp) {
                console.log('--jsonp', jsonp);
                let json1 = {}
                let that = this
                json1.latitude = jsonp.latitude
                json1.longitude = jsonp.longitude
                json1.local = jsonp.local
                json1.patrolDate = jsonp.patrolDate
                json1.userId = G.Storage.get('userInfo')['id']
                let users = []
                console.log(jsonp.unit);
                if (jsonp.unit.userId) {
                    users.push(jsonp.unit.userId)
                }
                that.setData({
                    param: json1,
                    unitsg: jsonp.units,
                    inventoryId: jsonp.inventoryId,
                    dispatchUserIDList: users,
                    dispatchUser: users[0],
                    applicant: G.Storage.get('userInfo')['userId'],
                })
                let user1 = [...users]
                let user2 = []
                for (let i = 0; i < user1.length; i++) {
                    G.get('/api/model/user', {
                        id: user1[i]
                    }).then(res => {
                        user2.push(res.name)
                        if (i == user1.length - 1) {
                            user2.push('不指定')
                            that.setData({
                                dispatchUserNameList: user2,
                            })
                        }
                    })
                }
                that.getResolveUser()
            },
            getResolveUser() {
                let that = this
                G.get('/api/model/user').then(res => {
                    if (!res.errorMsg) {
                        let userNameList = ['不指定']
                        res.forEach(i => {
                            userNameList.push(i.name)
                        })
                        that.setData({
                            userList: res,
                            userNameList: userNameList,
                        })
                    }
                })
            },
            ///
            test() {},

            bindinput(e) {
                console.log(e, 'eee')
                this.setData({
                    description: e.detail.value
                })
            },
            bindPickerunitChange(e) {
                console.log(e)
                const value = e.detail.value
                this.setData({
                    unitIndex:value,
                    dispatchUser:this.data.units[value].userId
                })
            },
            selectGrid(){
                let tab = this.data.tabs[this.data.tabIndex]
                if(this.data.timer){
                    clearInterval(this.data.timer)
                    this.data.timer = 0
                }
                this.selectComponent('#gridSelect').open({
                    latitude:this.data.latitude,
                    longitude:this.data.longitude,
                    address:this.data.address,
                    selectId:this.data.units[this.data.unitIndex][tab.value == 'grid' ? 'id' : 'inventoryId'],
                    tab
                })
            },
            changeGrid(event){
                // if(!event.detail.units){//关闭按钮
                //     this.data.timer = setInterval(()=>{
                //         this.getLocation()
                //     },1000 * 60 * 1)
                //     return
                // }
                this.setData({
                    units: event.detail.units,
                    unitIndex: event.detail.unitIndex,
                    dispatchUser:event.detail.userId
                })
                if(this.data.timer && event.detail.event != 1) {
                    clearInterval(this.data.timer)
                    this.data.timer = 0
                    // this.data.timer = setInterval(()=>{
                    //     this.getLocation()
                    // },1000 * 60 * 1)
                }
            },
            toSelectDeduction() {
                let that = this
                wx.navigateTo({
                    // url: '/pages/check/deductionSelect/index?resourceTypeId=&type=' + this.data.type,
                    url: `/pages/check/deductionSelect/index?resourceTypeId=${this.data.tabs[this.data.tabIndex].ids}&type=${this.data.type}`,
                    events: {
                        // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                        acceptDataFromOpenedPage: function ({
                            list,
                            type,
                            resourceTypeId
                        }) {
                            console.log(list, type, '拿到数据')

                            let total = 0
                            let deductionIdList = []
                            let description = []
                            list.forEach(item => {
                                total += Number(item.grade)
                                deductionIdList.push(item.id)
                                description.push(item.name)
                            })
                            let tabIndex = 0
                            that.data.tabs.forEach((item,i) => {
                                if(item.ids.indexOf(resourceTypeId) >= 0){
                                    tabIndex = i
                                }
                            })
                            that.setData({
                                deductionList: list,
                                type: type,
                                gradeTotal: total.toFixed(2),
                                //description:description.join(';'),
                                deductionIdList
                            })
                            if(resourceTypeId && tabIndex != that.data.tabIndex) that.changeTab(tabIndex)
                        }
                    }
                })
            },
            selectLocation() {
                wx.chooseLocation({
                    latitude:this.data.latitude,
                    longitude:this.data.longitude,
                    success:res=>{
                        if(this.data.timer) {
                            clearInterval(this.data.timer)
                            this.data.timer = 0
                        }
                        this.getGrid(res.longitude,res.latitude,res.address)
                    }
                })
            },
            // 删除图片
            delPic(e) {
                const {
                    index
                } = e.currentTarget.dataset

                let uploadList = [...this.data.picList]
                uploadList.splice(index, 1)

                this.setData({
                    picList: uploadList
                })
            },
            upload(e) {
                const {
                    type
                } = e.currentTarget.dataset
                let _self = this;

                if (this.data.picList.length >= 5) return wx.showToast({
                    title: '最多上传5张',
                    icon: 'none'
                })
                wx.chooseMedia({
                    count: 1,
                    mediaType: ['image'],
                    sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
                    sourceType: ['album','camera'], //从相册选择
                    success(res) {
                        console.log(res, '选择图片')
                        const tempFilePaths = res.tempFiles;
                        _self.chooseMediaa(tempFilePaths)
                    },
                    error: function (e) {
                        console.log(e);
                    }
                });

            },
            uploadRequest(img) {
                let _self = this;

                if (this.data.picList.length >= 5) return wx.showToast({
                    title: '最多上传5张',
                    icon: 'none'
                })
                wx.showLoading({
                    title: '上传中...',
                })

                const uploadTask = wx.uploadFile({
                    url: G.Storage.get('APIURL') + '/upload',
                    filePath: img,
                    name: 'file',
                    header: {
                        'token': G.Storage.get('userInfo').token
                    },
                    success(rej) {

                        try {
                            let showUrl = JSON.parse(rej.data).id
                            let url = G.Storage.get('APIURL') + '/file/' + showUrl
                            console.log(url, 'url')
                            let uploadList = [..._self.data.picList, {
                                url,
                                showUrl
                            }]
                            console.log(uploadList, 'uploadList')
                            _self.setData({
                                picList: uploadList,
                            })
                            wx.hideLoading()
                            // _self.chooseMedia(img)
                        } catch (e) {
                            //TODO handle the exception
                        }
                    },
                    fail(err) {
                        console.log(err)
                    }
                });
            },
            submit() {
                let that = this
                let {
                    type,
                    deductionIdList,
                    description,
                    picList,
                    gradeTotal,
                    latitude,
                    longitude,
                    unitId,
                    unitName,
                    unitIndex,
                    address
                } = that.data
                if(!description) {
                    description = this.data.deductionList[0].name
                    if(this.data.deductionList[1]) description += ';' + this.data.deductionList[1].name
                    if(this.data.deductionList[2]) description += ';' + this.data.deductionList[2].name
                    description = description.trim()
                }
                if(that.data.tabIndex) description += '(' + this.data.units[this.data.unitIndex].name + '-' + this.data.units[unitIndex].typeName + ')'
                if (picList.length == 0) {
                    wx.showToast({
                        title: '请上传图片',
                        icon: 'none'
                    })
                    return
                } else {
                    this.setData({ submiting:true })
                    if(deductionIdList.length == 0){
                        that.submitg()
                    }else{
                        let imgUrlList = picList.map(item => item.url)
                        const params = {
                            deductionIdList,
                            description,
                            imgUrlList,
                            "number": gradeTotal,
                            type,
                            latitude,
                            longitude,
                            gridId:this.data.units[unitIndex].id,
                            address,
                            "userId": G.Storage.get('userInfo').userId

                        }
                        if(this.data.time) params.assessTime = G.date(this.data.time).Format('yyyy-MM-dd hh:mm:ss')
                        //上报权重
                        // if(this.data.units[unitIndex].inventoryId){
                        //     G.get(G.Storage.get('JAVAURL') + '/sample/addWeight', {
                        //         id: this.data.units[unitIndex].inventoryId,
                        //         weight: 2
                        //     }).then(res => {
                        //         console.log('--res', res);
                        //     })
                        // }
                        G.post(javaUrl + '/assess/save', params).then(rej => {
                            if (rej.status == 200) {
                                ///
                                that.submitg(rej.data)
                                let newUnClickedList = G.Storage.get('newUnClickedList')
                                if(newUnClickedList) {
                                    if(newUnClickedList.length){
                                        wx.setStorage({
                                            key: 'imgList',
                                            data: newUnClickedList
                                        })
                                    }else{
                                        wx.removeStorageSync('imgList')
                                    }
                                    G.Storage.remove('newUnClickedList')
                                }
                            } else {
                                wx.showToast({
                                    title: rej.message,
                                    icon: 'none'
                                })
                            }
                        })
                    }
                }
            },
            getDistance(lat1, lng1, lat2, lng2) {
                lat1 = lat1 || 0;
                lng1 = lng1 || 0;
                lat2 = lat2 || 0;
                lng2 = lng2 || 0;
                var rad1 = lat1 * Math.PI / 180.0;
                var rad2 = lat2 * Math.PI / 180.0;
                var a = rad1 - rad2;
                var b = lng1 * Math.PI / 180.0 - lng2 * Math.PI / 180.0;
                var r = 6378137;
                var distance = r * 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(rad1) * Math.cos(rad2) * Math.pow(Math.sin(b / 2), 2)));
                return distance;
            },
            getGrid(longitude,latitude,address){
                if(longitude){
                    this.setData({
                        latitude,
                        longitude,
                        address:address || this.data.address
                    })
                }else{
                    latitude = this.data.latitude
                    longitude = this.data.longitude
                    address = this.data.address
                }
                this.selectComponent('#gridSelect').getDefault({
                    latitude,
                    longitude,
                    address,
                    pageSize:1,
                    tab:this.data.tabs[this.data.tabIndex]
                })
            },
            getLocation() {
                if(!this.data.unNow){
                    wx.getLocation({
                        type: 'gcj02',
                        success:res=> {
                            G.get('/v1/map/geocodeRegeo',{
                                latitude:res.latitude,
                                longitude:res.longitude
                            }).then(location => {
                                let address = location.regeocode ? location.regeocode.formatted_address : ''
                                this.getGrid(res.longitude,res.latitude,address)
                            })
                        }
                    })
                    if(!this.data.timer){
                        this.data.timer = setInterval(()=>{
                            this.getLocation()
                        },1000 * 30)
                    }
                }else{
                    this.getGrid(this.data.longitude,this.data.latitude)
                }
                
            },
            onShareAppMessage(event){
                return {
                    title:'请及时处理！',
                    path:'/pages/flow/detail/index?taskId=' + this.data.taskId
                }
            },
            // onShow(){
            //     if(this.loaded) {
            //         this.getLocation()
            //     }
            // },
            // onHide(){
            //     if(this.data.timer) {
            //         clearInterval(this.data.timer)
            //         this.data.timer = 0
            //     }
            // },
            onUnload(){
                if(this.data.timer) {
                    clearInterval(this.data.timer)
                    this.data.timer = 0
                }
            }
        },
        mounted(opt) {
            if (opt.param) {
                let jsonp = JSON.parse(opt.param)
                this.getInitParam(jsonp)
            }
            let data = { type:opt.type || 1, applicant:G.Storage.get('userInfo').userId}
            let newClickedList = G.Storage.get('newClickedList')
            if(newClickedList && newClickedList.length){
                data.picList = newClickedList && newClickedList.length ? newClickedList : []
                data.latitude = newClickedList[0].latitude
                data.longitude = newClickedList[0].longitude
                data.address = newClickedList[0].address
                data.unNow = true
                data.taskId2 = newClickedList[0].taskId
                data.time = newClickedList.time
                data.zlxd = opt.zlxd
                G.Storage.remove('newClickedList')
            }
            G.get('/model/grid',{},null,{storageName:'modelgrid'}).then(res => {
                data.tabs = res.resType.attr.actions
                this.setData(data)
                this.getLocation()
                this.loaded = true
                wx.hideShareMenu({
                    menus: ['shareAppMessage', 'shareTimeline']
                })
            })
        }
    })
})(wx.$)